<template>
  <div>
    <a-avatar size="large" :src="headPortraitNow || defaultAvatar" @click="changeHead" />&nbsp;&nbsp;
    <a-dropdown>
      <a class="ant-dropdown-link" @click="e => e.preventDefault()" style=" height：8px; ">
        <span :style="loc==='entry'?{'color':'#fff'}:{}">{{userName}}</span>
        <a-icon type="down" :style="loc==='entry'?{'color':'#fff'}:{}" />
      </a>
      <a-menu slot="overlay">
        <a-menu-item>
          <a href="javascript:;" @click="modifyPassword">修改密码</a>
        </a-menu-item>
        <a-menu-item>
          <a href="javascript:;" @click="logout">退出登录</a>
        </a-menu-item>
        <a-menu-item>
          <a href="https://shimo.im/docs/HgW8YqjDVKPtYy6g" target="_blank">操作手册</a>
        </a-menu-item>
      </a-menu>
    </a-dropdown>

    <a-modal
      title="修改密码"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :wrapper-col="wrapperCol">
        <a-form-model-item prop="oldPassword" hasFeedback>
          <a-input type="password" v-model="form.oldPassword" placeholder="原密码" autocomplete="off">
            <a-icon slot="prefix" type="lock" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="newPassword" hasFeedback>
          <a-input type="password" v-model="form.newPassword" placeholder="新密码" autocomplete="off">
            <a-icon slot="prefix" type="lock" />
          </a-input>
        </a-form-model-item>
        <a-form-model-item prop="checkPass" hasFeedback>
          <a-input type="password" v-model="form.checkPass" placeholder="确认新密码" autocomplete="off">
            <a-icon slot="prefix" type="lock" />
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 修改头像 -->
    <a-modal
      width="500px"
      title="修改头像"
      destroyOnClose
      centered
      :visible="visible1"
      :confirm-loading="confirmLoading1"
      @ok="handleOk1"
      @cancel="handleCancel1"
    >
      <a-form-model
        ref="ruleForm1"
        :model="form1"
        :rules="rules1"
        :label-col="{span:7}"
        :wrapper-col="{span:17}"
      >
        <a-form-model-item prop="headPortrait" label="头像">
          <ud-upload :length="1" @uploadFile="pictureUpload" :fatherList="picList" head />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import md5 from 'md5'
import { Dropdown, Menu, Input } from 'ant-design-vue'
import store from 'store'
import upload from '@/components/UpLoad'
import { updatePassword, userLogout, updateSelfHeadPortrait } from '@/api'
import defaultAvatar from '@/../static/images/defaultAvatar.png'

export default {
  name: 'login-user',
  props: ['loc'],
  data () {
    let validateNewPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.form.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    let validateNewPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认新密码'))
      } else if (value !== this.form.newPassword) {
        callback(new Error('两次输入新密码不一致'))
      } else {
        callback()
      }
    }
    return {
      wrapperCol: { span: 20, offset: 2 },
      form: {
        oldPassword: '',
        newPassword: '',
        checkPass: ''
      },
      form1: {
        headPortrait: ''
      },
      headPortraitNow: '',
      rules1: {
      },
      rules: {
        oldPassword: [
          { required: true, message: '原密码必须输入', trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6~16位密码', trigger: 'blur' }
        ],
        newPassword: [
          { validator: validateNewPass, trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6~16位密码', trigger: 'blur' }
        ],
        checkPass: [
          { validator: validateNewPass2, trigger: 'blur' },
          { min: 6, max: 16, message: '请输入6~16位密码', trigger: 'blur' }
        ]
      },
      visible: false,
      confirmLoading: false,
      visible1: false,
      confirmLoading1: false,
      defaultAvatar
    }
  },
  computed: {
    userName: () => store.get('userName'),
    picList () {
      return this.form1.headPortrait ? [this.form1.headPortrait] : []
    }
  },
  components: {
    [Dropdown.name]: Dropdown,
    [Menu.name]: Menu,
    [Menu.Item.name]: Menu.Item,
    [Input.name]: Input,
    'ud-upload': upload
  },
  methods: {
    modifyPassword () {
      this.visible = true
    },
    handleOk (e) {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.confirmLoading = true
          updatePassword({
            oldPassword: md5(this.form.oldPassword),
            newPassword: md5(this.form.newPassword),
            account: store.get('token')
          }).then(rsp => {
            this.$message.success('修改成功')
            this.confirmLoading = false
            this.logout()
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel (e) {
      this.visible = false
      this.$refs['ruleForm'].resetFields()
    },
    changeHead () {
      this.form1.headPortrait = this.headPortraitNow
      this.visible1 = true
    },
    pictureUpload (val) {
      this.form1.headPortrait = val
    },
    handleOk1 (e) {
      this.$refs['ruleForm1'].validate(valid => {
        if (valid) {
          this.confirmLoading1 = true
          updateSelfHeadPortrait({ headPortrait: this.form1.headPortrait || '' }).then(rsp => {
            this.confirmLoading1 = false
            this.$message.success('修改成功')
            this.headPortraitNow = this.form1.headPortrait
            store.set('headPortrait', this.form1.headPortrait) // 更新
            this.visible1 = false
          }).catch(() => { this.confirmLoading1 = false })
        }
      })
    },
    handleCancel1 (e) {
      this.visible1 = false
      this.$refs['ruleForm1'].resetFields()
    },
    logout () {
      const token = store.get('token')
      userLogout({ token }).then(rsp => {
        store.remove('token')
        this.$router.push('/user/login')
      })
    }
  },
  mounted () {
    this.headPortraitNow = store.get('headPortrait')
  }
}
</script>

<style lang="less" scoped>
.ant-dropdown-link {
  color: #333333;
}
</style>
